﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ImgURLUploader
{
    class Images
    {

        public static string GetImageFile(string dir,string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                WebResponse response = request.GetResponse();
                //imageStrCookie = "";
                //if (response.Headers.HasKeys() && null != response.Headers["Set-Cookie"])
                //{
                //    imageStrCookie = response.Headers.Get("Set-Cookie");
                //}
                int i = 0;

                string prefix = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string filepath = "";
                while (true)
                {
                    filepath = dir + "\\" + prefix + i+".jpg";
                    if (File.Exists(filepath))
                    {
                        Thread.Sleep(500);
                        i++;
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                Stream sr=  response.GetResponseStream();
                Image img= Image.FromStream(sr);
                img.Save(filepath);
                return filepath;
            }catch(Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
